#!/usr/bin python3
# -*- encoding: utf-8 -*-
"""
@author: 关河九州
@contact: 
@software: PyCharm
@file: utils
@time: 2022/2/18 17:28
"""
from decimal import Decimal
from string import Template

import yaml
from faker import Faker
from jsonpath import jsonpath
from loguru import logger

""" =============== 工具方法封装 =============== """


class Utils:
    @classmethod  # 可以直接类名.方法名()来调用，不需要实例化，不需要self参数，但第一个参数需要是表示自身类的cls参数，可以来调用类的方法、类的属性、实例化对象等
    def handle_yaml(cls, file_name):
        """
        读取yaml文件
        :param file_name:
        :return:
        """
        try:
            yaml_data = yaml.safe_load(open(file_name, encoding='utf-8'))
        except Exception as e:
            logger.error(f'yaml文件读取失败，文件名称：{file_name}')
            raise e
        else:
            return yaml_data

    @classmethod
    def handle_token(cls, response):
        """
        组装token
        :param response:
        :return:
        """
        token_type = jsonpath(response.json(), '$..token_type')[0]
        token_value = jsonpath(response.json(), '$..token')[0]
        token = f'{token_type} {token_value}'
        return token

    @classmethod
    def handle_template(cls, source_data, replace_data: dict, ):
        """
        替换文本变量
        :param source_data:源数据
        :param replace_data:替换数据
        :return:
        """
        # string.Template 字符串模板替换
        # safe_substitute替换存在的字典值，保留未存在的替换符号
        res = Template(str(source_data)).safe_substitute(**replace_data)
        return yaml.safe_load(res)

    @classmethod
    def handle_decimal(cls, data: int):
        """
        将小数或整数转换为两位数小数
        :param data:
        :return:
        """
        x = '{0:.2f}'.format(float(data))
        return Decimal(x)

    @classmethod
    def handle_random_phone(cls):
        """
        生成随机手机号
        :return:
        """
        fake = Faker(locale='zh_CN')
        phone_number = fake.phone_number()
        return phone_number

    @classmethod
    def handle_random_name(cls):
        """
        生成随机姓名
        :return:
        """
        fake = Faker(locale='zh_CN')
        name = fake.name()
        return name

    @classmethod
    def handle_random_address(cls):
        """
        生成随机地址
        :return:
        """
        fake = Faker(locale='zh_CN')
        address = fake.address()
        return address


if __name__ == '__main__':
    a = Utils.handle_random_address()
    print(a)
